// 中文转utf-8 utf-16编码
export function encodeStr(str: string, code = 8) {
    const s = encodeURIComponent(str);
    const arr = s.match(/%\w*/g);
    const a = arr?.reduce((a, b) => a + `/${parseInt(b.replace('%', '0x'), 16).toString(8)}`, '');

    const b = arr?.reduce((a, b) => a + b.replace('%', '/x'), '');

    return code === 8 ? a : b;
}

// utf-8 utf-16编码转中文
export function decodeStr(str: string, code = 8) {
    let s: string | undefined = '';
    if (code === 8) {
        s = str.match(/\d+/g)?.reduce((a, b) => a + `%${parseInt(b, 8).toString(16).toUpperCase()}`, '');
    } else if (code === 16) {
        s = str.match(/(?<=\/x)\w+/g)?.reduce((a, b) => a + `%${b}`.toUpperCase(), '');
    }

    return s ? decodeURIComponent(s) : '';
}
// eg
// let a = encodeStr('啊', 8);
// let b = decodeStr(a, 8);
// console.log(a, b);
// let c = encodeStr('啊', 16);
// let d = decodeStr(c, 16);
// console.log(c, d);

export const setCssVar = (prop: string, val: string, dom = document.documentElement) => {
    dom.style.setProperty(prop, val);
};

export const getCssVar = (prop: string, dom = document.documentElement) => getComputedStyle(dom).getPropertyValue(prop);
